package com.wanrui.shiro.config;

import com.wanrui.shiro.bean.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Configuration;

/**
 * 自定义的realm类
 */
@Configuration
public class UserRealm extends AuthorizingRealm {

    // 自动注入dao查询数据库
    // 认证里认证有没有这个人
    // 授权里再去查询这个人的权限

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");

        // 开始授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // 从subject里获取用户
        User user = (User) principalCollection.getPrimaryPrincipal();
        System.out.println(user);
        simpleAuthorizationInfo.addStringPermission("user:add");
        return simpleAuthorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String user = token.getUsername();// 获取账号
        String password = String.valueOf(token.getPassword());
        // 这里去数据库里查询
        System.out.println(user);
        System.out.println(password);

        // 模拟数据库查询回来的结果
        User admin = new User("admin", "123");

        if (!user.equals(admin.getName())){
            return null;  // 自动会匹配到UnknownAccountException异常
        }
        // 匹配密码,shiro自动处理，只需要把数据库查出来的密码给他
        // new SimpleAuthenticationInfo 是简单认证，明文，后面需要MD5加盐
//        return new SimpleAuthenticationInfo("","123","");
        // 这里可以传递user对象给授权页面
        return new SimpleAuthenticationInfo(admin,"123","");
    }
}
